package people.paper.tv.activity.home;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.umeng.analytics.MobclickAgent;

import java.io.Serializable;

import people.paper.tv.activity.home.view.HomeView;
import people.paper.tv.utils.ui.Common;

/**
 * The type Home fragment.
 */
public abstract class HomeFragment extends Fragment {
    /**
     * Test view.
     *
     * @param mContext     the m context
     * @param homeFragment the home fragment
     * @return the view
     */
   /* public static View test(Context mContext, final HomeFragment homeFragment) {
        LinearLayout _root = new LinearLayout(mContext);
        _root.setOrientation(LinearLayout.VERTICAL);
        TextView textView = new TextView(mContext);
        textView.setText(homeFragment.NAME);
        _root.addView(textView);

        Button p = new Button(mContext);
        p.setText("prev");
        p.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                homeFragment.prev();
            }
        });
        _root.addView(p);

        Button n = new Button(mContext);
        n.setText("next");
        n.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                homeFragment.next();
            }
        });
        _root.addView(n);
        return _root;
    }
*/

    /**
     * The interface Fragment model.
     */
    public interface FragmentModel {
        /**
         * Create.
         *
         * @param context the contexts
         */
        void create(Context context);
    }

    /**
     * The interface Fragment presenter.
     *
     * @param <VIEW>  the type parameter
     * @param <MODEL> the type parameter
     */
    public interface FragmentPresenter<VIEW extends FragmentView, MODEL extends FragmentModel> {
        /**
         * Create.
         *
         * @param context the context
         * @param view    the view
         * @param model   the model
         */
        void create(Context context, VIEW view, MODEL model, HomeFragment homeFragment);

        /**
         * Start.
         */
        void start();

        /**
         * Resume.
         */
        void resume();

        /**
         * Pause.
         */
        void pause();

        void onActivityStart();

        void onActivityResume();

        void onActivityPause();

        void onActivityStop();

        void destroy();
    }

    /**
     * The interface Fragment view.
     *
     * @param <PRESENTER> the type parameter
     */
    public interface FragmentView<PRESENTER extends FragmentPresenter> {
        /**
         * Create view.
         *
         * @param context      the context
         * @param presenter    the presenter
         * @param homeFragment the home fragment；view主要用里面的 {@link HomeFragment#next} {@link HomeFragment#prev}方法
         * @return the view
         */
        View create(Context context, PRESENTER presenter, HomeFragment homeFragment);
        boolean changeFragmentFocus(boolean isLeft);
        boolean setLayoutFocus();
        void resume();
        void pause();
        void onActivityResume();
        void onActivityPause();
        void destroy();
    }


    /**
     * The interface Home fragment manager.
     */
    public interface HomeFragmentManager {
        /**
         * Gets animator listener adapter.
         *
         * @return the animator listener adapter
         */
        AnimatorListenerAdapter getAnimatorListenerAdapter();

        /**
         * Prev.
         */
        boolean prev(int id);

        /**
         * Next.
         */
        boolean next(int id);

        boolean click(int preId,int id);

        HomeFragment getCurrentHomeFragment();
    }

    private static class FractionTranslateLayout extends RelativeLayout implements Serializable {
        private int screenWidth;
        private float fractionX;

        /**
         * Instantiates a new Fraction translate layout.
         *
         * @param context the context
         */
        public FractionTranslateLayout(Context context) {
            super(context);
        }

        /**
         * Instantiates a new Fraction translate layout.
         *
         * @param context the context
         * @param attrs   the attrs
         */
        public FractionTranslateLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        /**
         * Instantiates a new Fraction translate layout.
         *
         * @param context      the context
         * @param attrs        the attrs
         * @param defStyleAttr the def style attr
         */
        public FractionTranslateLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }

        protected void onSizeChanged(int w, int h, int oldW, int oldH) {

            // Assign the actual screen width to our class variable.
            screenWidth = w;

            super.onSizeChanged(w, h, oldW, oldH);
        }

        /**
         * Gets fraction x.
         *
         * @return the fraction x
         */
        public float getFractionX() {
            return fractionX;
        }

        /**
         * Sets fraction x.
         *
         * @param xFraction the x fraction
         */
        public void setFractionX(float xFraction) {
            this.fractionX = xFraction;

            // When we modify the xFraction, we want to adjust the x translation
            // accordingly.  Here, the scale is that if xFraction is -1, then
            // the layout is off screen to the left, if xFraction is 0, then the
            // layout is exactly on the screen, and if xFraction is 1, then the
            // layout is completely offscreen to the right.
            setX((screenWidth > 0) ? (xFraction * screenWidth) : 0);

            if (xFraction == 1 || xFraction == -1) {
                setAlpha(0);
            } else if (xFraction < 1 /* enter */ || xFraction > -1 /* exit */) {
                if (getAlpha() != 1) {
                    setAlpha(1);
                }
            }
        }
    }

    /**
     * The Name.
     */
    public final String NAME = this.toString();
    private HomeFragmentManager homeFragmentManager;
    private FractionTranslateLayout contentView;
    public HomeView homeView;
    private boolean isLeft;

    /**
     * Instantiates a new Home fragment.
     */
    public HomeFragment() {
    }

    /**
     * Gets fragment view.
     *
     * @return the fragment view
     */
    protected abstract FragmentView getFragmentView();

    /**
     * Gets fragment presenter.
     *
     * @return the fragment presenter
     */
    protected abstract FragmentPresenter getFragmentPresenter();

    /**
     * Gets fragment model.
     *
     * @return the fragment model
     */
    protected abstract FragmentModel getFragmentModel();

    protected void setHomeView(HomeView view) {
        homeView = view;
    }

    protected void setTabId(int i) {
        id = i;
    }

    protected int getTabId() {
        return id;
    }

    private FragmentView view;
    private FragmentPresenter presenter;
    private FragmentModel model;
    private int id;

    private boolean bStarted = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        contentView = new FractionTranslateLayout(getActivity());
        contentView.setClipChildren(false);
        contentView.setClipToPadding(false);

        view = getFragmentView();
        presenter = getFragmentPresenter();
        model = getFragmentModel();
        model.create(getActivity());
        presenter.create(getActivity(), view, model, this);
        Log.d("FFF", NAME + " onCreate");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.d("FFF", NAME + " onHiddenChanged " + hidden);
        if (!hidden) {
            if (!bStarted) {
                bStarted = true;
                contentView.addView(view.create(getActivity(), presenter, this));
                presenter.start();
                Log.d("FFF", NAME + " presenter start id:" + id);
            }
            Common.CurTab = id;
            presenter.resume();
            view.resume();
            MobclickAgent.onPageStart(NAME);
//            if(view.changeFragmentFocus(isLeft)){
//                homeView.changeSelectedToBar(id);
//            }else {
                homeView.changeFocusToBar(id);
//            }
            Log.d("FFF", NAME + " presenter resume");
        } else {
            if (bStarted) {
                presenter.pause();
                view.pause();
                MobclickAgent.onPageEnd(NAME);
                homeView.placeFocus(true);
                Log.d("FFF", NAME + " presenter pause");
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        presenter.onActivityStart();
        Log.d("FFF", NAME + " onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.onActivityResume();
        view.onActivityResume();
        Log.d("FFF", NAME + " onResume");
    }

    @Override
    public void onPause() {
        presenter.onActivityPause();
        view.onActivityPause();
        super.onPause();
        Log.d("FFF", NAME + " onPause");
    }

    @Override
    public void onStop() {
        presenter.onActivityStop();
        super.onStop();
        Log.d("FFF", NAME + " onStop");
    }

    @Override
    public void onDestroy() {
        presenter.destroy();
        view.destroy();
        super.onDestroy();
        Log.d("FFF", NAME + " onDestroy");
    }

    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return contentView;
    }

    public FragmentView getViewImpl(){
        return view;
    }

    /**
     * Sets home fragment manager.
     *
     * @param homeFragmentManager the home fragment manager
     */
    public final void setHomeFragmentManager(HomeFragmentManager homeFragmentManager) {
        this.homeFragmentManager = homeFragmentManager;
    }

    /**
     * 显示下一个fragment界面
     */
    public final void next(int id) {
        isLeft = false;
        if (homeFragmentManager != null)
            homeFragmentManager.next(id);
    }

    /**
     * 显示上一个fragment界面
     */
    public final void prev(int id) {
        isLeft = true;
        if (homeFragmentManager != null)
            homeFragmentManager.prev(id);
    }

    public final boolean isCurrentFragment() {
        if (homeFragmentManager != null)
            return homeFragmentManager.getCurrentHomeFragment() == this;
        return false;
    }

    @Override
    public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
        if (homeFragmentManager != null) {
            try {
                Animator anim = AnimatorInflater.loadAnimator(getActivity(), nextAnim);
                anim.addListener(homeFragmentManager.getAnimatorListenerAdapter());
                return anim;
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
        return super.onCreateAnimator(transit, enter, nextAnim);
    }
}